import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dartssh2/dartssh2.dart';
import 'package:xterm/xterm.dart' as xterm;
import 'package:flutter_gbk2utf8/flutter_gbk2utf8.dart';
import '../../../common/models/server_model.dart';
import '../../../common/services/server_service.dart';
import '../../../common/utils/index.dart';

class TerminalController extends GetxController {
  final ServerService _serverService = Get.find<ServerService>();
  late final String serverId;
  
  Rx<ServerModel?> server = Rx<ServerModel?>(null);
  SSHClient? sshClient;
  SSHSession? sshSession;
  
  // 终端相关
  late final xterm.Terminal terminal;
  late final xterm.TerminalController terminalController;
  
  RxBool isConnected = false.obs;
  RxBool isLoading = false.obs;
  RxString errorMessage = ''.obs;
  
  // 字体大小控制（用于缩放）
  RxDouble fontSize = 14.0.obs;  // 默认字体大小
  static const double minFontSize = 8.0;   // 最小字体大小
  static const double maxFontSize = 32.0;  // 最大字体大小
  
  // 编码缓存
  bool _useGBK = false;

  @override
  void onInit() {
    super.onInit();
    debugPrint('🎬 TerminalController: onInit');
    
    serverId = Get.parameters['id'] ?? '';
    debugPrint('   服务器ID: $serverId');
    
    if (serverId.isEmpty) {
      debugPrint('❌ TerminalController: 服务器 ID 为空');
      LoadingUtil.error('服务器 ID 无效');
      Get.back();
      return;
    }
    
    // 初始化终端
    terminal = xterm.Terminal(
      maxLines: 10000,  // 保留 10000 行历史
    );
    
    terminalController = xterm.TerminalController();
    
    // 设置终端输入回调
    terminal.onOutput = (data) {
      _handleTerminalInput(data);
    };
    
    _loadServer();
  }

  Future<void> _loadServer() async {
    debugPrint('📋 TerminalController: 加载服务器信息 - ID: $serverId');
    
    server.value = _serverService.getServer(serverId);
    if (server.value == null) {
      debugPrint('❌ TerminalController: 服务器不存在 - ID: $serverId');
      LoadingUtil.error('服务器不存在');
      Get.back();
      return;
    }
    
    debugPrint('✅ TerminalController: 服务器信息加载成功');
    debugPrint('   名称: ${server.value!.name}');
    debugPrint('   地址: ${server.value!.connectionString}');
    
    // 自动连接终端
    await connectTerminal();
  }

  /// 连接终端
  Future<void> connectTerminal() async {
    if (server.value == null) {
      debugPrint('❌ TerminalController: 服务器信息为空，无法连接');
      return;
    }
    
    isLoading.value = true;
    errorMessage.value = '';
    
    try {
      LoadingUtil.show('正在连接终端 ${server.value!.name}...');
      debugPrint('🚀 TerminalController: 开始连接终端...');
      
      // 1. 检查是否已有 SSH 连接
      sshClient = _serverService.getClient(serverId);
      
      if (sshClient == null) {
        // 需要先建立 SSH 连接
        debugPrint('🔌 TerminalController: 建立 SSH 连接...');
        await _serverService.connectServer(serverId);
        sshClient = _serverService.getClient(serverId);
        
        if (sshClient == null) {
          throw Exception('无法建立 SSH 连接');
        }
      }
      
      // 2. 创建 Shell 会话
      debugPrint('🐚 TerminalController: 创建 Shell 会话...');
      sshSession = await sshClient!.shell(
        pty: SSHPtyConfig(
          width: terminal.viewWidth,
          height: terminal.viewHeight,
        ),
      );
      
      // 3. 监听 SSH 输出
      sshSession!.stdout.listen(
        (data) => _handleSSHOutput(data),
        onError: (error) {
          debugPrint('❌ TerminalController: SSH stdout 错误 - $error');
          _writeError('SSH 输出错误: $error');
        },
        onDone: () {
          debugPrint('🔚 TerminalController: SSH stdout 关闭');
          if (isConnected.value) {
            _writeInfo('\r\n\x1b[33m[连接已断开]\x1b[0m\r\n');
            isConnected.value = false;
          }
        },
      );
      
      sshSession!.stderr.listen(
        (data) => _handleSSHOutput(data),
        onError: (error) {
          debugPrint('❌ TerminalController: SSH stderr 错误 - $error');
        },
      );
      
      isConnected.value = true;
      LoadingUtil.success('终端连接成功！');
      debugPrint('✅ TerminalController: 终端连接成功');
      
      // 4. 欢迎消息
      _writeInfo('✅ 已连接到 ${server.value!.name}\r\n');
      _writeInfo('终端大小: ${terminal.viewWidth}×${terminal.viewHeight}\r\n');
      _writeInfo('---\r\n');
      
    } catch (e) {
      errorMessage.value = e.toString();
      debugPrint('❌ TerminalController: 连接失败');
      debugPrint('   错误信息: $e');
      
      LoadingUtil.error('连接失败: $e');
      _writeError('连接失败: $e');
      
    } finally {
      isLoading.value = false;
      LoadingUtil.dismiss();
    }
  }

  /// 处理 SSH 输出（解码并写入终端）
  void _handleSSHOutput(List<int> data) {
    try {
      // 智能解码：UTF-8 优先，失败则用 GBK
      String text;
      
      if (_useGBK) {
        // 已知是 GBK 服务器，直接用 GBK
        text = gbk.decode(data);
      } else {
        // 尝试 UTF-8
        text = utf8.decode(data, allowMalformed: true);
        
        // 检查是否有替换字符（�）
        if (text.contains('�')) {
          debugPrint('⚠️ TerminalController: UTF-8 解码失败，切换到 GBK');
          try {
            text = gbk.decode(data);
            _useGBK = true;  // 记住这是 GBK 服务器
          } catch (e) {
            debugPrint('❌ TerminalController: GBK 解码也失败 - $e');
            // 保留 UTF-8 结果
          }
        }
      }
      
      // 写入终端
      terminal.write(text);
      
    } catch (e) {
      debugPrint('❌ TerminalController: 输出解码失败 - $e');
    }
  }

  /// 处理终端输入（发送到 SSH）
  void _handleTerminalInput(String data) {
    if (sshSession == null || !isConnected.value) {
      debugPrint('⚠️ TerminalController: 未连接，忽略输入');
      return;
    }
    
    try {
      // 编码并发送
      final bytes = _useGBK ? gbk.encode(data) : utf8.encode(data);
      // 转换为 Uint8List
      final uint8bytes = Uint8List.fromList(bytes);
      sshSession!.stdin.add(uint8bytes);
    } catch (e) {
      debugPrint('❌ TerminalController: 输入编码失败 - $e');
      _writeError('输入失败: $e');
    }
  }

  /// 发送特殊按键
  void sendKey(String sequence) {
    if (sshSession == null || !isConnected.value) {
      return;
    }
    
    try {
      // 直接发送到 SSH
      final uint8bytes = Uint8List.fromList(utf8.encode(sequence));
      sshSession!.stdin.add(uint8bytes);
    } catch (e) {
      debugPrint('❌ TerminalController: 按键发送失败 - $e');
    }
  }

  /// 调整终端大小
  void resizeTerminal(int width, int height) {
    if (sshSession == null) return;
    
    try {
      sshSession!.resizeTerminal(width, height);
      debugPrint('📐 TerminalController: 终端大小已调整为 $width×$height');
    } catch (e) {
      debugPrint('❌ TerminalController: 调整终端大小失败 - $e');
    }
  }

  /// 清屏
  void clearScreen() {
    terminal.write('\x1b[2J\x1b[H');  // ANSI 清屏命令
  }

  /// 增加字体大小
  void increaseFontSize() {
    if (fontSize.value < maxFontSize) {
      fontSize.value = (fontSize.value + 1).clamp(minFontSize, maxFontSize);
      debugPrint('🔠 TerminalController: 字体大小增加到 ${fontSize.value}');
    }
  }

  /// 减小字体大小
  void decreaseFontSize() {
    if (fontSize.value > minFontSize) {
      fontSize.value = (fontSize.value - 1).clamp(minFontSize, maxFontSize);
      debugPrint('🔠 TerminalController: 字体大小减小到 ${fontSize.value}');
    }
  }

  /// 重置字体大小
  void resetFontSize() {
    fontSize.value = 14.0;
    debugPrint('🔠 TerminalController: 字体大小重置为 ${fontSize.value}');
  }

  /// 设置字体大小（用于手势缩放）
  void setFontSize(double size) {
    fontSize.value = size.clamp(minFontSize, maxFontSize);
  }

  /// 断开连接
  void disconnect() {
    debugPrint('🔌 TerminalController: 断开终端连接');
    
    try {
      sshSession?.close();
      sshSession = null;
      
      isConnected.value = false;
      _writeInfo('\r\n\x1b[33m[已断开连接]\x1b[0m\r\n');
      
      LoadingUtil.info('终端已断开');
    } catch (e) {
      debugPrint('❌ TerminalController: 断开连接失败 - $e');
    }
  }

  // ========== 辅助方法 ==========

  /// 写入信息消息（绿色）
  void _writeInfo(String message) {
    terminal.write('\x1b[32m$message\x1b[0m');
  }

  /// 写入错误消息（红色）
  void _writeError(String message) {
    terminal.write('\r\n\x1b[31m[错误] $message\x1b[0m\r\n');
  }

  @override
  void onClose() {
    debugPrint('🔚 TerminalController: onClose');
    
    // 断开连接
    sshSession?.close();
    
    // 清理终端控制器
    terminalController.dispose();
    
    super.onClose();
  }
}

